package com.eb.buybuybuy.util;

import com.eb.buybuybuy.constant.Configuration;
import com.eb.buybuybuy.context.TransactionContext;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class MysqlUtil {
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("驱动不存在");
        }
    }

    public static Connection getConnection() {
        try {
            return DriverManager.getConnection("jdbc:mysql://localhost:3306/" + Configuration.DATABASE, Configuration.DB_USER, Configuration.DB_PASSWORD);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static int update(String sql, Object... arg) throws SQLException {
        Connection connection;
        // 如果开启事务，获取当前连接，如果没有，获取新连接
        if (TransactionContext.isOpening()) {
            connection = TransactionContext.getConnection();
        } else {
            connection = MysqlUtil.getConnection();
        }

        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < arg.length; i++) {
            Object s = arg[i];
            preparedStatement.setObject(i + 1, s);
        }
        int num = preparedStatement.executeUpdate();

        // 没开事务，关闭连接
        if (!TransactionContext.isOpening()) {
            connection.close();
        }
        return num;
    }

    public static <T> List<T> query(String sql, Class<T> clazz, Object... arg) throws SQLException, ReflectiveOperationException {
        Connection connection = getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < arg.length; i++) {
            Object s = arg[i];
            preparedStatement.setObject(i + 1, s);
        }
        ResultSet resultSet = preparedStatement.executeQuery();

        List<T> list = new ArrayList<>();
        while (resultSet.next()) {
            T c = clazz.newInstance();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                String fieldName = field.getName();
                Object value = resultSet.getObject(fieldName);
                field.setAccessible(true);
                // 把这个字段设置在c对象上，值为value
                field.set(c, value);
            }
            list.add(c);
        }
        connection.close();
        return list;
    }

}
